package com.zookeeper;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
@Slf4j
public class ZookeeperTest {
    private static final String CONNECT_STRING = "192.168.4.96:2181";
    private static final  int SESSION_TIMEOUT = 30*1000;
    private static ZooKeeper zookeeper = null;
    private static CountDownLatch downLatch = new CountDownLatch(1);
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        Watcher watcher = new Watcher(){
            @SneakyThrows
            @Override
            public void process(WatchedEvent event) {
                zookeeper.getData("/config",true,null);
                if(event.getType().equals(Event.EventType.None)
                        && event.getState().equals(Event.KeeperState.SyncConnected)){
                    log.info(" connected=============..." );
                    downLatch.countDown();
                }
            }
        };

        zookeeper = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT,watcher);
        log.info("connecting ================...");
        downLatch.countDown();
        Stat stat = new Stat();
        byte[] bytes = zookeeper.getData("/config", true, stat);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = objectMapper.writeValueAsBytes("name:wlb");
        Stat stat1 = zookeeper.setData("/config", data, stat.getVersion());

        Thread.sleep(500000);


    }


}
